const BaseDataAdapter = require('./../../base-data-adapter');
const functions = require('./../../../functions');
const FunctionVariable = require('./../../../mongo/function-variable');
const utility = require('./../../../utility');

class DataAdapter extends BaseDataAdapter {
  async getFileVariables(fileId, versionId) {
    const variables = await FunctionVariable.aggregate([
      {
        $match: { versionId, fileId },
      },
      {
        $lookup: {
          from: 'functions', localField: 'functionId', foreignField: '_id', as: 'func',
        },
      },
    ]);
    return variables.map((variable) => {
      if (!utility.isEmpty(variable.func)) {
        variable.mangledId = [`${fileId}_${variable.func[0].mangledId}`];
      }
      delete variable.func;
      return variable;
    });
  }

  async getIntegratedFuncsVariables(functionId) {
    const [func, variable] = await Promise.all([
      functions.getFunction(functionId),
      functions.getRelationFuncsVariables(functionId),
    ]);
    if (func) {
      variable.mangledId.add(`${func.fileId}_${func.mangledId}`);
    }
    variable.mangledId = [...variable.mangledId];
    return variable;
  }
}

module.exports = DataAdapter;
